package com.ttl.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ttl.web.entity.GoodsCollect;
import com.ttl.web.service.GoodsCollectService;
import com.ttl.web.utils.ResultVo;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * 失物招领商品管理
 * @author 上玄
 */
@RestController
@RequestMapping("/api/collect")
public class GoodsCollectController {
    @Resource
    private GoodsCollectService goodsCollectService;

    /**
     * 收藏商品
     * @param goodsCollect
     */
    @PostMapping("/collect")
    public ResultVo collect(@RequestBody GoodsCollect goodsCollect) {
        // 判断是否收藏
        QueryWrapper<GoodsCollect> query = new QueryWrapper<>();
        query.lambda().eq(GoodsCollect::getGoodsId, goodsCollect.getGoodsId())
                .eq(GoodsCollect::getUserId, goodsCollect.getUserId());
        GoodsCollect one = goodsCollectService.getOne(query);
        // 没有收藏
        if (one == null) {
            goodsCollect.setCollectTime(new Date());
            if (goodsCollectService.save(goodsCollect)) {
                return ResultVo.success("收藏成功！");
            }
        } else {
            // 已经收藏，取消收藏
            if (goodsCollectService.remove(query)) {
                return ResultVo.success("取消收藏成功！");
            } else {
                return ResultVo.error("取消收藏失败！");
            }
        }
        return ResultVo.error("收藏失败！");
    }

    /**
     * 是否收藏
     * @param goodsCollect
     */
    @GetMapping("/hasCollect")
    public ResultVo hasCollect(GoodsCollect goodsCollect){
        // 判断是否收藏
        QueryWrapper<GoodsCollect> query = new QueryWrapper<>();
        query.lambda().eq(GoodsCollect::getGoodsId, goodsCollect.getGoodsId())
                .eq(GoodsCollect::getUserId, goodsCollect.getUserId());
        GoodsCollect one = goodsCollectService.getOne(query);
        if(one == null){
            return ResultVo.success("查询成功", "0");
        }else{
            return ResultVo.success("查询成功", "1");
        }
    }


}
